{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9932a712-28c7-4e05-a39c-ee14239cabc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "db417cc7-7587-4465-a5d4-d793d6ca6a60",
   "metadata": {},
   "outputs": [],
   "source": [
    "def Initial_miu(X, k):\n",
    "    miu = [np.random.randint(X.shape[1])]\n",
    "    while len(miu) < k:\n",
    "        dis = np.ones(X.shape[1]) * np.infty\n",
    "        for i in range(X.shape[1]):\n",
    "            if i in miu:\n",
    "                continue;\n",
    "            for j in miu:\n",
    "                dis[i] = min(dis[i], np.sum((X[:, i] - X[:, j]) ** 2))\n",
    "        miu.append(np.argmax(dis))\n",
    "    for i in range(k):\n",
    "        miu[i] = X[:, i].copy()\n",
    "    return np.array(miu)\n",
    "\n",
    "def K_means(X, k):\n",
    "    threshold = 1e-6\n",
    "    \n",
    "    #初始化均值\n",
    "    miu = Initial_miu(X, k)\n",
    "    \n",
    "    while 1:\n",
    "        temp = miu.copy()\n",
    "        #计算类别\n",
    "        cluster = np.zeros((0, X.shape[1]))\n",
    "        for i in range(miu.shape[0]):\n",
    "            cluster = np.vstack([cluster, np.sum((X - miu) ** 2, axis=0)])\n",
    "        cluster = np.argmin(cluster, axis=0)\n",
    "        \n",
    "        #更新均值\n",
    "        for i in range(miu.shape[0]):\n",
    "            miu[i] = np.average([X[:, j] for j in range(X.shape[1]) if cluster[j] == i], axis=0)\n",
    "        \n",
    "        if np.sum((temp - miu) ** 2) < threshold:\n",
    "            break\n",
    "    \n",
    "    return miu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d77bd2e-bc8a-48b3-b71d-77e58f1175df",
   "metadata": {},
   "outputs": [],
   "source": [
    "def GMM(X, k, echo=100000):\n",
    "    #X(n, m)\n",
    "    #初始化\n",
    "    miu = K_means(X, k)\n",
    "    sigma = np.array([np.eye(X.shape[1]) * 0.1 for _ in range(k)])\n",
    "    alpha = np.ones((k, 1)) / k\n",
    "    \n",
    "    for _ in range(echo):\n",
    "        #E步\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c744556e-5a61-4986-adce-8a17c3410ca1",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
